/*
 * Copyright 2011 Rolf Aden
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

package com.ec;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import junit.framework.TestCase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.TaskAttemptID;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.mapreduce.contrib.DatastoreMapper;

/**
 * Base class for mapper related test cases to set up the environment and 
 * provide a few utility functions.
 * 
 * @author Rolf Aden
 */
public abstract class MapperTestCase extends TestCase {

	protected final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
	protected DatastoreService ds;

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		this.helper.setUp();
		this.ds = DatastoreServiceFactory.getDatastoreService();		
	}

	@Override
	protected void tearDown() throws Exception {
		super.tearDown();
		this.helper.tearDown();
	}
	
	protected Mapper<Key,Entity,NullWritable,NullWritable>.Context createTestContext(DatastoreMapper mapper) throws IOException, InterruptedException {
		return createTestContext(mapper, null);
	}
	
	@SuppressWarnings("unchecked")
	protected Mapper<Key, Entity, NullWritable, NullWritable>.Context createTestContext(
			DatastoreMapper mapper, String xml) throws IOException, InterruptedException {

		Configuration conf = new Configuration(false);
		if (xml != null) {
			conf.addResource(new ByteArrayInputStream(xml.getBytes()));
		}

		return mapper.new AppEngineContext(conf,
				new TaskAttemptID("foo", 1, true, 1, 1),
				null, null, null, null, null);
	}
	
}
